package com.key.utils;

import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.*;

import org.jbarcode.JBarcode;
import org.jbarcode.JBarcodeFactory;
import org.jbarcode.encode.Code128Encoder;
import org.jbarcode.encode.InvalidAtributeException;
import org.jbarcode.paint.BaseLineTextPainter;
import org.jbarcode.paint.TextPainter;
import org.jbarcode.paint.WidthCodedPainter;
import org.jbarcode.util.ImageUtil;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;

public class JbarcodeUtil {

    // 设置条形码高度
    private static final int BARCODE_HEIGHT = 60;
    // 设置条形码默认分辨率
    private static final int BARCODE_DPI = ImageUtil.DEFAULT_DPI;
    // 设置条形码字体样式
    private static final String FONT_FAMILY = "新宋体";
    // 设置条形码字体大小
    private static final int FONT_SIZE = 20;
    // 设置条形码文本
    public static String TEXT = "";
    // 创建jbarcode
    private static JBarcode jbc = null;

    // 生成条形码最下面一行；
    private static String name = "";

    static JBarcode getJBarcode() throws InvalidAtributeException {
/**
 * 参考设置样式： barcode.setEncoder(Code128Encoder.getInstance()); //设置编码
 * barcode.setPainter(WidthCodedPainter.getInstance());// 设置Painter
 * barcode.setTextPainter(BaseLineTextPainter.getInstance()); //设置TextPainter
 * barcode.setBarHeight(17); //设置高度
 * barcode.setWideRatio(Double.valueOf(30).doubleValue());// 设置宽度比率
 * barcode.setXDimension(Double.valueOf(2).doubleValue()); // 设置尺寸，大小 密集程度
 * barcode.setShowText(true); //是否显示文本 barcode.setCheckDigit(true); //是否检查数字
 * barcode.setShowCheckDigit(false); //是否显示检查数字*/


        if (jbc == null) {
            // 生成code128
            jbc = JBarcodeFactory.getInstance().createCode128();
            jbc.setEncoder(Code128Encoder.getInstance());
            // jbc.setTextPainter(CustomTextPainter.getInstance());
            jbc.setTextPainter(CustomTextPainter.getInstance());
            // jbc.setWideRatio(Double.valueOf(1).doubleValue());
            // jbc.setXDimension(Double.valueOf(1).doubleValue());
            jbc.setBarHeight(BARCODE_HEIGHT);
            // jbc.setXDimension(1);
            jbc.setShowText(true);

        }
        return jbc;
    }


    /*public static void createBarcode(String message, File file, String text) {
        try {

            FileOutputStream fos = new FileOutputStream(file);
            createBarcode(message, fos, text);
            fos.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }*/


    /*public static void createBarcode(String message, OutputStream os, String text) {
        try {
            String[] a = message.split(",");
            name = a[0] + " " + a[1];
            // 设置条形码文本
            TEXT = text;
            System.out.println(TEXT);
            // 创建条形码的BufferedImage图像
            BufferedImage image = getJBarcode().createBarcode("   " + a[0]);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write( image, "jpg", baos );
            //转换为MultipartFile
            MultipartFile multipartFile = new MockMultipartFile("1.jpg", baos.toByteArray());
            ImageUtil.encodeAndWrite(image, ImageUtil.PNG, os, 10, 0);

            os.flush();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }*/

    public static MultipartFile createBarcode(String message, String text) {
        try {

            name = message;
            // 设置条形码文本
            TEXT = text;
            System.out.println(TEXT);
            // 创建条形码的BufferedImage图像
            BufferedImage image = getJBarcode().createBarcode(name);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write( image, "jpg", baos );
            //转换为MultipartFile
            MultipartFile multipartFile = new MockMultipartFile("1.jpg", baos.toByteArray());

            return multipartFile;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    /*
     *
     * 静态内部类 自定义的 TextPainter， 允许定义字体，大小，文本等 参考底层实现：BaseLineTextPainter.getInstance()
     */


    protected static class CustomTextPainter implements TextPainter {
        private static CustomTextPainter instance = new CustomTextPainter();

        public static CustomTextPainter getInstance() {
            return instance;
        }

        public void paintText(BufferedImage barCodeImage, String text, int width) {
            String[] a = TEXT.split("\n");

            System.out.println(barCodeImage.getWidth());
            // 绘图
            System.out.println(barCodeImage.getHeight());

            Graphics g2d = barCodeImage.getGraphics();
            // 创建字体
            Font font = new Font("防宋", Font.PLAIN, 12);

            g2d.setFont(font);
            FontMetrics fm = g2d.getFontMetrics();

            g2d.setColor(Color.WHITE); // 143 30

            //g2d.fillRect(0, 0, 200, a.length*20+10);

            g2d.fillRect(0, 0, 200, a.length*20+40);

           // g2d.fillRect(0, 300, 200, 100);

            // g2d.fillRect(0, 0, 200, barCodeImage.getHeight() * 1 / 20);
            // g2d.fillRect(0, barCodeImage.getHeight() - (height * 9 / 10),
            // barCodeImage.getWidth(), (height * 9 / 10));
            // 55 143 111
            g2d.setColor(Color.BLACK);

            // 绘制文本
            Integer height=0;
            for (String s : a) {
                height+=20;
                g2d.drawString(s, 10, height);
            }
            //g2d.drawString(TEXT, barCodeImage.getWidth() / 3 * 2 - 5, 20);
            // 绘制条形码
            g2d.drawString(name, 10, a.length*20+20);

        }
    }




}
